package han.temp;

import com.han.http.client.paramter.RequestHeader;
import han.fetch.Fetcher;
import org.json.JSONArray;
import org.json.JSONObject;

import java.util.Arrays;
import java.util.List;
import java.util.Random;

import static com.han.http.util.Print.printlnErr;
import static com.han.http.util.Print.printlnInfo;
import static han.util.OtherTools.convertStringToUTF8;

/**
 * @author: Han
 * @date: 2018/8/8 10:47
 * @dscription: 获取所有融资项目领域
 */
public class TestProId {
    public static void main(String... args) {
        List<String> labelList = Arrays.asList("电商", "社交", "硬件", "文娱传媒", "工具", "消费生活", "金融", "医疗健康",
                "企业服务", "旅游", "房产家居", "教育", "汽车交通", "物流", "人工智能", "无人机", "机器人", "VR·AR", "体育",
                "农业", "共享经济", "出海", "消费升级");
        RequestHeader[] requestHeader = {
                new RequestHeader("User-Agent", "36kr-Tou-Android/4.1.2 (MI 6; Android 8.0.0; Scale/1920x1080)"),
                new RequestHeader("Cookie", "kr_plus_id=15145236; kr_plus_token=bLxGQvYJibigvSxRMoMogfm78mK_131_35711___; krid_user_version=1"),
                new RequestHeader("Host", "rong.36kr.com"),
                new RequestHeader("Connection", "Keep-Alive"),
                new RequestHeader("Accept-Encoding", "gzip")
        };
        Fetcher fetcher = new Fetcher();
        for (String label : labelList) {
            boolean hasNext = true;
            int page = 1;
            while (hasNext) {
                try {
                    String jsonStr = fetcher.getInfoByGet("https://rong.36kr.com/api/mobi-investor/search/v2/label?keyword="
                                    + convertStringToUTF8(label) + "&page=" + page + "&pageSize=20",
                            requestHeader, 1000 * 10, 1000 * 10, null);
                    hasNext = getName(jsonStr);
                    page++;
                } catch (Exception e) {
                    printlnErr(label + "," + page);
                    break;
                } finally {
                    try {
                        Thread.sleep(1000 * 3 + new Random().nextInt(1000 * 3));
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    private static boolean getName(String str) {
        boolean hasNext = false;
        JSONArray dataArray = new JSONObject(str).getJSONObject("data").getJSONArray("data");
        for (int i = 0; i < dataArray.length(); i++) {
            JSONObject object = dataArray.getJSONObject(i);
            String name = object.getString("name");
            String hex = convertStringToUTF8(name);
            printlnInfo(name + ":  " + hex);
            hasNext = true;
        }
        return hasNext;
    }
}
